<?php
class UserUtility
{
    public static function getById($userId)
    {
        return UserModel::model()->findByPk($userId);
    }
    
    public static function add($userId)
    {
        // user info from facebook
        $userInfo = FacebookUtility::getUserInfo($userId);
        
        // add location
        $location = self::addLocation($userInfo['current_location']);
        $hometown = self::addLocation($userInfo['hometown_location']);;

        // change birthday format
        $birthday = DateUtility::convertFormat($userInfo['birthday_date'], 'm/d/Y', 'Y-m-d');
        
        // gender
        $gender = self::convertToGenderId($userInfo['sex']);

        // add user
        $user = new UserModel();
        $user->id = $userId;
        $user->name = $userInfo['name'];
        $user->first_name = $userInfo['first_name'];
        $user->last_name = $userInfo['last_name'];
        $user->birthday = $birthday;
        $user->profile_url = $userInfo['profile_url'];
        $user->username = $userInfo['username'];
        $user->email = $userInfo['email'];
        $user->location_id = $location->id;
        $user->hometown_id = $hometown->id;
        $user->gender_id = $gender;
        $user->last_login = '0000-00-00';
        $user->search_purpose_id = CONST_SEARCH_PURPOSE_DATE;
        $user->save();

        // avatar
        $avatar = PhotoUtility::addByUrl($userId, $userInfo['pic_big']);
        $user->avatar_id = $avatar;
        $user->save();

        // download album profile
        $params = array();
        $params['userId'] = $userId;
        $params['fbToken'] = FacebookUtility::getAccessToken();
        GearmanUtility::doBackground(ENUM_GEARMAN_JOB_DOWNLOAD_ALBUM_PROFILE, $params);

        // snapshot preference
        $age = DateUtility::calcAge($birthday);
        $preference = new SnapshotPreferenceModel();
        $preference->id = $userId;
        $preference->interest_id = CONST_INTEREST_NEW_PEOPLE;
        $preference->gender_id = (int) !$gender;
        $preference->age_from = $age - 5;
        $preference->age_to = $age + 5;
        $preference->city_id = $location->city_id;
        $preference->distance = 100;
        $preference->save();

        // search preference
        $age = DateUtility::calcAge($birthday);
        $preference = new SearchPreferenceModel();
        $preference->id = $userId;
        $preference->interest_id = CONST_INTEREST_NEW_PEOPLE;
        $preference->gender_id = (int) !$gender;
        $preference->age_from = $age - 5;
        $preference->age_to = $age + 5;
        $preference->city_id = $location->city_id;
        $preference->distance = 100;
        $preference->save();

        // user mapping
        $mapping = new UserMappingModel();
        $mapping->id = $userId;
        $mapping->search_purpose_id = $user->search_purpose_id;
        $mapping->gender_id = $gender;
        $mapping->year_of_birth = DateUtility::calcYearOfBirth($birthday);
        $mapping->city_id = $location->city_id;
        $mapping->distance = $location->distance;
        $mapping->save();

        // log
        $params = array();
        $params[] = CONST_LOG_CREATE_USER;
        $params[] = $userId;
        $params[] = $gender;
        $params[] = $birthday;
        $params[] = null;
        $params[] = $user->email;
        GearmanUtility::doBackground(ENUM_GEARMAN_JOB_LOG, $params);

        return $user;
    }

    public static function daily($userId)
    {
        // update fb data
        $params = array();
        $params['userId'] = $userId;
        $params['fbToken'] = FacebookUtility::getAccessToken();
        GearmanUtility::doBackground(ENUM_GEARMAN_JOB_UPDATE_FB_DATA, $params);
        
        // build snapshot
        SnapshotUtility::build($userId);
    }

    public static function login($userId)
    {
        // update login data
        $lastLogin = new CDbExpression('NOW()');
        $fbToken = FacebookUtility::getAccessToken();
        UserModel::model()->updateByPk($userId, array('last_login' => $lastLogin, 'fb_token' => $fbToken));

        // log
        $params = array();
        $params[] = CONST_LOG_LOGIN;
        $params[] = $userId;
        GearmanUtility::doBackground(ENUM_GEARMAN_JOB_LOG, $params);
    }

    public static function addLocation($info)
    {
        // default
        if($info === null)
        {
            $info = array('id' => CONST_DEFAULT_LOCATION_ID);
        }

        // not exist
        $location = LocationUtility::getById($info['id']);
        if(!$location)
        {
            $location = LocationUtility::add($info['id'], $info['name'], $info['latitude'], $info['longitude']);
        }

        return $location;
    }

    public static function addWork($userId, $workId, $workName)
    {
        $work = WorkUtility::getById($workId);
        if(!$work)
        {
            WorkUtility::add($workId, $workName);
        }

        UserModel::model()->addWork($userId, $workId);
    }
    
    public static function deleteWork($userId)
    {
        UserModel::model()->deleteWorkByUserId($userId);
    }

    public static function addEducation($userId, $educationId, $educationName)
    {
        $education = EducationUtility::getById($educationId);
        if(!$education)
        {
            EducationUtility::add($educationId, $educationName);
        }

        UserModel::model()->addEducation($userId, $educationId);
    }
    
    public static function deleteEductaion($userId)
    {
        UserModel::model()->deleteEducationByUserId($userId);
    }

    public static function updateSearchPurpose($userId, $searchPurposeId)
    {
        UserModel::model()->updateByPk($userId, array('search_purpose_id' => $searchPurposeId));
    }

    public static function getInfo($userId)
    {
        // get data from db
        /* @var UserModel $user */
        $criteria = new CDbCriteria();
        $criteria->with = array('gender', 'location', 'hometown', 'works', 'educations', 'avatar', 'photos');
        $criteria->together = true;
        $user = UserModel::model()->findByPk($userId, $criteria);
        if(!$user)
        {
            return null;
        }

        // info
        $info = $user->getAttributes(array('id', 'name', 'birthday', 'profile_url'));
        $info['gender'] = $user->gender->getAttributes(array('id', 'name'));
        $info['location'] = $user->location->getAttributes(array('id', 'name'));
        $info['hometown'] = $user->hometown->getAttributes(array('id', 'name'));
        $info['works'] = array();
        foreach($user->works as $work)
        {
            /* @var WorkModel $work */
            $info['works'][$work->id] = $work->getAttributes(array('id', 'name'));
        }
        $info['educations'] = array();
        foreach($user->educations as $education)
        {
            /* @var EducationModel $education */
            $info['educations'][$education->id] = $education->getAttributes(array('id', 'name'));
        }
        $info['avatar'] = $user->avatar->getAttributes(array('id', 'filename'));
        $info['photos'] = array();
        foreach($user->photos as $photo)
        {
            /* @var PhotoModel $photo */
            $info['photos'][] = $photo->getAttributes(array('id', 'filename'));
        }
        return $info;
    }

    public static function getInfos($userIds)
    {
        $infos = array();
        foreach($userIds as $userId)
        {
            $infos[] = self::getInfo($userId);
        }
        return $infos;
    }
    
    private static function convertToGenderId($fbStr)
    {
        switch($fbStr)
        {
            case 'male':
                return CONST_GENDER_FEMALE;
            case 'female':
                return CONST_GENDER_MALE;
            default:
                return CONST_GENDER_UNKNOW;
        }
    }
}